package com.parttime.actions;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.Cookie;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.factory.annotation.Autowired;

import com.opensymphony.xwork2.ModelDriven;
import com.parttime.service.LoginManager;

@SuppressWarnings("serial")

@Namespace("")
@ParentPackage("kkkjjjj")
@Action(interceptorRefs={@InterceptorRef("systemInterceptor")})
@ExceptionMappings({@ExceptionMapping(exception = "java.lange.RuntimeException", result = "500")})    
public class LoginUserAction extends CommonAction implements ModelDriven<LoginVO>{

	private LoginVO user = new LoginVO();
	
	@Autowired
	private LoginManager loginManager;

	@SuppressWarnings("rawtypes")
	@Action(value = "login",results={@Result(name="success",location="/index.jsp")})
	public String login() throws Exception {
		System.out.print(user);
		Map map = loginManager.login(user);
		Object u = map.get("User");
		if(u != null){
			//保存用户信息记录到session 
			session.put("User", u);
			
			//记录cookie
			Cookie[] cookies = request.getCookies();
			if(cookies != null&&user.getAuto_login().equals("on")){
				for (Cookie c : cookies) {
					if ((c.getName().equals("name") || c.getName().equals("account")) && c.getValue()!= "") {
						String value = URLDecoder.decode(c.getValue(),"utf-8");
						System.out.println(value);
					}
				}
			}
		}else{
			this.addActionMessage((String)map.get("msg"));
		}
		return "success";
	}
	@Action(value="validateAuth")
	public void validateAuth() throws IOException{
		response.setCharacterEncoding("utf-8");
		String auth=(String) session.get("auth");
		if(!auth.equals(request.getParameter("auth")))
			response.getWriter().print("验证码错误");
			
	}
	
	@Action(value="sendEmail")
	public void sendEmail() throws IOException{
		request.setCharacterEncoding("utf-8");
		String toEmail=request.getParameter("email");
		String sendEmail="send_context@sina.com";
		String phone=request.getParameter("phone");
		
		
		Properties properties = new Properties();
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.host", "smtp.sina.com");
		properties.put("mail.transport.protocol", "SMTP");
		Session sess = Session.getInstance(properties,authenticator);
		Message mess = new MimeMessage(sess);
		try{
			
			mess.setFrom(new InternetAddress(sendEmail));
			mess.setRecipient(RecipientType.TO, new InternetAddress(toEmail));	
			String subject="亲爱的用户"+phone+"：您好!\n";
			Integer random=(int) (Math.random()*10000);
			session.put("auth", random.toString());
			String sp=" 您收到这封这封电子邮件是因为您 (也可能是某人冒充您的名义) "
					+ "申请了一个新的密码。假如这不是您本人所申请, "
					+ "请不用理会这封电子邮件, 但是如果您持续收到这类的信件骚扰, "
					+ "请您尽快联络管理员。\n";
			String tell="验证码为：";
			mess.setSubject("[兼职中心] 找回您的账号密码   ");
			mess.setSentDate(new Date());
			mess.setText(subject+sp+tell+String.valueOf(random));
			
	        Transport.send(mess);
		}catch(AddressException ae){
			ae.printStackTrace();
			response.getWriter().print("出错，请重新获取验证码");
		}catch(MessagingException me){
			me.printStackTrace();
			response.getWriter().print("出错，请重新获取验证码");
		}
	}
	private	static Authenticator authenticator = new Authenticator() {
		@Override
		protected PasswordAuthentication getPasswordAuthentication() {		
			return new PasswordAuthentication("send_context@sina.com", "sendcontext");
		}
	};	
	@Action(value = "userLoginOut",results={@Result(name="loginOut",location = "gainLoginPage",type="chain")})
	public String userLoginOut ()throws Exception{
		session.clear();
		return "loginOut";
	}
	
	@Override
	public LoginVO getModel() {
		return user;
	}
}
